package com.ece750.client;

import java.util.logging.Logger;

import com.ece750.client.channel.Channel;
import com.ece750.client.channel.ChannelFactory;
import com.ece750.client.channel.SocketError;
import com.ece750.client.channel.SocketListener;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class GTalkClient implements EntryPoint {
	
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";
	
	private String username = "";
	private String password = "";
	private int currentRow = 0;
	
	private final GTalkServiceAsync serviceAsync = GWT.create(GTalkService.class);
	
	private static final Logger _logger = Logger.getLogger("TalkLogger");
	
	public void onModuleLoad() {
		_logger.info("Module loaded");
		
		final Grid chat = new Grid(20, 1);
		chat.addStyleName("chatArea");
		final ScrollPanel p = new ScrollPanel();
		p.setSize("400px", "400px");
		p.add(chat);
		RootPanel.get("textAreaContainer").add(p);
		
		final TextBox entry = new TextBox();
		entry.addStyleName("entryBox");
		RootPanel.get("textEntryContainer").add(entry);
		
		Label l = new Label("Connecting to chat server...");
		l.setStylePrimaryName("connectingText");
		chat.setWidget(currentRow, 0, l);
		currentRow++;
		
		serviceAsync.getToken("d4dietri", new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Failed to get api token");
			}

			@Override
			public void onSuccess(String result) {
				String channelApiToken = result;
				
				Channel channel = ChannelFactory.createChannel(channelApiToken);
				channel.open(new SocketListener() {
				        @Override
				        public void onMessage(String message) {
				        	Label l = new Label("Professor:" + message);
				        	l.setStylePrimaryName("profText");
				        	
				        	if (currentRow >= chat.getRowCount()) {
				        		chat.resizeRows(currentRow+5);
				        	}
				        	
				        	chat.setWidget(currentRow, 0, l);
				        	p.scrollToBottom();
				        	currentRow++;
				        }
				        @Override
				        public void onOpen() {
				        	Label l = new Label("Connected to chat server, you may now talk");
				        	l.setStylePrimaryName("connectedText");
				        	chat.setWidget(currentRow, 0, l);
				        	currentRow++;
				        }
						@Override
						public void onError(SocketError error) {
							Window.alert("Error received: " + error.getDescription());
						}
						@Override
						public void onClose() {
							Window.alert("You have been disconnected.");
						}
				});
			}
			
		});
		
		//Create the interface, just a big text box and a place to enter text
		
		class MessageHandler implements KeyUpHandler {
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					if (!entry.getText().trim().equals("")) {
						String entryText = entry.getText();
						
						chat.getElement().setScrollTop(chat.getElement().getScrollHeight());
						Label l = new Label("You:" + entryText);
			        	l.setStylePrimaryName("studentText");
			        	
			        	if (currentRow >= chat.getRowCount()) {
			        		chat.resizeRows(currentRow+5);
			        	}
			        	
			        	chat.setWidget(currentRow, 0, l);
			        	p.scrollToBottom();
			        	currentRow++;
			        	
						entry.setText("");
						
						_logger.info("In message handler stuff");
						
						serviceAsync.sendMessage(entryText, new AsyncCallback<String>() {

							public void onFailure(Throwable caught) {
								_logger.info("Failed");
								_logger.info(caught.getMessage());
							}

							public void onSuccess(String result) {
								_logger.info(result);
							}
							
						});
					}
				}
			}
		}
		
		entry.addKeyUpHandler(new MessageHandler());
	}
	

}

